// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 自动关闭警告消息
    const alerts = document.querySelectorAll('.alert-dismissible');
    alerts.forEach(function(alert) {
        setTimeout(function() {
            const bsAlert = new bootstrap.Alert(alert);
            bsAlert.close();
        }, 5000); // 5秒后自动关闭
    });
    
    // 表格排序功能
    const sortableTables = document.querySelectorAll('.table-sortable');
    sortableTables.forEach(function(table) {
        const headers = table.querySelectorAll('th[data-sort]');
        headers.forEach(function(header) {
            header.addEventListener('click', function() {
                const sortKey = this.dataset.sort;
                const sortDirection = this.classList.contains('sort-asc') ? 'desc' : 'asc';
                
                // 清除所有表头的排序样式
                headers.forEach(h => {
                    h.classList.remove('sort-asc', 'sort-desc');
                    h.querySelector('i')?.remove();
                });
                
                // 设置当前表头的排序样式
                this.classList.add(`sort-${sortDirection}`);
                const icon = document.createElement('i');
                icon.className = `fas fa-sort-${sortDirection} ms-2`;
                this.appendChild(icon);
                
                // 执行排序逻辑
                sortTable(table, sortKey, sortDirection);
            });
        });
    });
    
    // 美化版确认删除对话框
    const deleteButtons = document.querySelectorAll('.btn-delete');
    deleteButtons.forEach(function(button) {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            const deleteUrl = this.getAttribute('href');
            
            Swal.fire({
                title: '确认删除',
                text: '您确定要删除此项吗？此操作不可恢复！',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: '是的，删除!',
                cancelButtonText: '取消',
                focusCancel: true,
                showClass: {
                    popup: 'animate__animated animate__fadeInDown'
                },
                hideClass: {
                    popup: 'animate__animated animate__fadeOutUp'
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = deleteUrl;
                }
            });
        });
    });
    
    // 图片预览功能
    const imgInputs = document.querySelectorAll('.img-input');
    imgInputs.forEach(function(input) {
        input.addEventListener('change', function() {
            const preview = document.getElementById(this.dataset.preview);
            if (preview && this.files && this.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    preview.src = e.target.result;
                    preview.style.display = 'block';
                };
                reader.readAsDataURL(this.files[0]);
            }
        });
    });
});

// 表格排序函数
function sortTable(table, sortKey, direction) {
    const tbody = table.querySelector('tbody');
    const rows = Array.from(tbody.querySelectorAll('tr'));
    
    // 排序行
    rows.sort(function(a, b) {
        let aValue = a.querySelector(`td[data-${sortKey}]`)?.getAttribute(`data-${sortKey}`) || 
                     a.querySelector(`td[data-${sortKey}]`)?.textContent.trim();
        let bValue = b.querySelector(`td[data-${sortKey}]`)?.getAttribute(`data-${sortKey}`) || 
                     b.querySelector(`td[data-${sortKey}]`)?.textContent.trim();
        
        // 尝试转换为数字
        if (!isNaN(aValue)) aValue = parseFloat(aValue);
        if (!isNaN(bValue)) bValue = parseFloat(bValue);
        
        if (direction === 'asc') {
            return aValue > bValue ? 1 : -1;
        } else {
            return aValue < bValue ? 1 : -1;
        }
    });
    
    // 重新插入排序后的行
    rows.forEach(function(row) {
        tbody.appendChild(row);
    });
}

// 价格计算函数
function calculateDiscount() {
    const originalPrice = document.getElementById('original_price').value;
    const discountPrice = document.getElementById('discount_price').value;
    
    if (originalPrice && discountPrice) {
        const discountRate = (discountPrice / originalPrice).toFixed(2);
        document.getElementById('discount_rate').value = discountRate;
        document.getElementById('discount_display').textContent = `折扣率: ${(discountRate * 100).toFixed(0)}%`;
    }
}

// 地图相关函数
function initMap(latitude, longitude, elementId) {
    if (typeof google !== 'undefined' && latitude && longitude) {
        const mapOptions = {
            center: { lat: parseFloat(latitude), lng: parseFloat(longitude) },
            zoom: 15
        };
        const map = new google.maps.Map(document.getElementById(elementId), mapOptions);
        
        // 添加标记
        new google.maps.Marker({
            position: { lat: parseFloat(latitude), lng: parseFloat(longitude) },
            map: map
        });
    }
} 